package com.dk.ssm.controller;

import com.dk.ssm.entity.Dept;
import com.dk.ssm.entity.Emp;
import com.dk.ssm.service.DeptService;
import com.dk.ssm.service.EmpService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class EmpController {
    private final EmpService empService;
    private final DeptService deptService;

    public EmpController(EmpService empService, DeptService deptService) {
        this.empService = empService;
        this.deptService = deptService;
    }

    @GetMapping("/emp")
    public String getAllEmp(Model model) {
        model.addAttribute("empList", empService.getAllEmp());
        return "empList";
    }

    @GetMapping("/emp/{id}/{option}")
    public ModelAndView getEmpById(@PathVariable Integer id, @PathVariable String option) {
        // 查询员工信息
        Emp emp = empService.getEmpById(id);
        // 查询部门信息
        List<Dept> deptList = deptService.getAllDept();

        ModelAndView modelAndView = new ModelAndView();
        if ("p".equals(option)){
            modelAndView.setViewName("empInfo");
        }else {
            modelAndView.setViewName("empEdit");
        }
        modelAndView.addObject("emp",emp);
        modelAndView.addObject("deptList",deptList);
        return modelAndView;
    }

    @PostMapping("/emp")
    public String addEmp(Emp emp) {
        empService.addEmp(emp);
        return "redirect:/emp";
    }

    @PutMapping("/emp")
    public String modifyEmp(Emp emp){
        empService.modifyEmp(emp);
        return "redirect:/emp";
    }

    @DeleteMapping("/emp/{id}")
    public String removeEmp(@PathVariable Integer id){
        empService.remove(id);
        return "redirect:/emp";
    }


    @GetMapping("/emp/addPage")
    public String addPage() {
        return "empAdd";
    }
}
